#include"stdafx.h"
#include"ServerDB.h"

bool ServerDB::DB_Drop(char *name, string &msg) {
	for (unsigned int i = 0; i < dbVector.size(); i++) {
		if (strcmp(dbVector[i].name, name) == 0) {
			CString dir;
			dir = dbVector[i].filename;
			DeleteDirectory(dir);
			dbVector.erase(dbVector.begin() + i);
			file.Remove(fileName);
			file.Open(fileName, CFile::modeCreate);
			file.Close();
			file.Open(fileName, CFile::modeReadWrite | CFile::typeBinary, NULL);
			DB_Struct db;
			for (unsigned int j = 0; j < dbVector.size(); j++) {
				file.Write(&dbVector[j], sizeof(dbVector[j]));
			}
			file.Close();
			msg = "successful !";
			return true;
		}
	}
	msg = "Incorrect database name !";
	return false;
}

bool ServerDB::DB_Create(char *name, string &msg) {
	DB_Struct db; Conversion(db.name, name);
	vector<DB_Struct>::iterator ret = find(dbVector.begin(), dbVector.end(), db);
	if (ret == dbVector.end()) {
		CString   strFolderPath;
		strFolderPath = name; strFolderPath = L"data\\" + strFolderPath;
		if (CreateDirectory(strFolderPath, NULL)) {
			CString logFile, descFile;
			logFile = name; logFile += L".log";
			descFile = name; descFile += L".tb";
			strFolderPath = strFolderPath + L"\\";
			logFile = strFolderPath + logFile;
			descFile = strFolderPath + descFile;
			file.Open(logFile, CFile::modeCreate | CFile::typeBinary, NULL);
			file.Close();
			file.Open(descFile, CFile::modeCreate | CFile::typeBinary, NULL);
			file.Close();
			DB_Struct db;
			db.crtime = CTime::GetCurrentTime();
			Conversion(db.name, name);
			char temp[256];
			sprintf_s(temp, "%s%s", "data//", name);
			Conversion(db.filename, temp);
			db.type = false;
			file.Open(fileName, CFile::modeWrite | CFile::typeBinary, NULL);
			file.SeekToEnd();
			file.Write(&db, 396);
			file.Close();
			dbVector.push_back(db);
			msg = "successful !";
			return true;
		}
		else {
			msg = "Failed to create folder !";
			return false;
		}
	}
	else {
		msg = "Database has already exist !";
		return false;
	}
	return false;
}

bool ServerDB::DB_Show(vector<string>& info) {
	if (dbVector.size() == 0) {
		return false;
	}
	for (unsigned int i = 0; i < dbVector.size(); i++) {
		info.push_back(dbVector[i].name);
	}
	return true;
}

bool  ServerDB::DB_Use(char* name, string &msg) {
	
	DB_Struct db; Conversion(db.name, name);
	vector<DB_Struct>::iterator ret = find(dbVector.begin(), dbVector.end(), db);
	if (ret == dbVector.end()) {
		msg = "Database not exist !";
		return false;
	}
	this->cur_db = name;
	msg = name;
	msg = "Database change to " + msg;
	return true;
}